var express = require("express");
var router = express.Router();
var db = require("../db/index");
var jwt = require("../jwt/index");

const seed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'Q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  '2', '3', '4', '5', '6', '7', '8', '9'
];

// 用于创建社团管理员时随机生成账号密码
function randomStr(size) {
  let seedlength = seed.length;//数组长度
  let createStr = '';
  for (let i = 0; i < size; i++) {
    let j = Math.floor(Math.random() * seedlength);
    createStr += seed[j];
  }
  return createStr;
}

// 后台管理员登录
router.post("/login", function (req, res) {
  let {type, username, password} = req.body;
  db.query(
      `SELECT * FROM ${type} WHERE username = '${username}' AND password = '${password}'`,
      function (err, rows = []) {
        if (rows.length > 0) {
          var token = jwt({
            id: rows[0].id,
            name: rows[0].username,
            type: type,
            society_id: rows[0].society_id || ' '
          });
          res.send({
            code: 200,
            message: '登录成功',
            data: {
              token
            }
          });
        } else {
          res.json({
            code: 201,
            message: err.message,
          });
        }
      }
  );
});

// 根据token获取后台管理员信息
router.get("/info", function (req, res) {
  if(req.auth.type !== 'admin2_account'){
    res.send({
      code: 200,
      data: {
        ...req.auth,
        avatar: "http://sso.njtc.edu.cn/files/2021/06/04/74964060b98ed9b8f45.png"
      }
    })
  }else {
    res.send({
      code: 200,
      data: {
        ...req.auth,
        avatar: "http://sso.njtc.edu.cn/files/2021/06/04/74964060b98ed9b8f45.png",
        ...{name:'社团管理员'}
      }
    })
  }

});

// 新增社团管理员
router.post('/addAdmin', function (req, res) {
  let {societyId, creationTime} = req.body;
  let username = randomStr(8);
  let password = randomStr(8);
  db.query(`INSERT INTO admin2_account SET ?`, {username, password, society_id: societyId, creationTime}, function (err) {
    if (err) {
      res.send({
        code: 10002,
        message: '添加新社团管理员失败'
      })
    } else {
      db.query(`UPDATE society SET haveAdmin = ? WHERE id = ${societyId}`, [1], function (err2) {
        if (!err2) {
          res.send({
            code: 200,
            message: '添加新社团管理员成功'
          })
        }
      })
    }
  })
})

// 获取所有社团管理员信息
router.get('/getAllAdmin', function (req, res) {
  let {pageNo, limit} = req.query;
  let start = (pageNo - 1) * limit;
  db.query(`SELECT a.*,s.title FROM admin2_account a JOIN society s ON a.society_id = s.id limit ${start},${limit}`, function (err, rows) {
    if (!err) {
      res.send({
        code: 200,
        message: '获取成功',
        data: {
          adminsInfo: rows
        }
      })
    } else {
      res.send({
        code: 10003,
        message: '社团管理员数据获取失败，请尝试刷新'
      })
    }
  })
})

// 根据id删除社团管理员
router.post('/delete', function (req, res) {
  let ids = req.body.ids;
  db.query(`DELETE FROM admin2_account WHERE id in (${ids})`, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '删除成功'
      })
    } else {
      res.send({
        code: 10011,
        message: '删除失败，请稍候重试！'
      })
    }
  })
})
module.exports = router;
